package com.jzoom.zoom.admin.utils;

import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;

import java.util.Collections;
import java.util.Map;


public class JsUtils {





    // 匿名函数
    private static String FORMAT = "(function(){\n%s\n})();";

    public static Object execute(String content, Object...args){
        return execute(content,Collections.EMPTY_MAP,args);
    }

    public static Object execute(String content,Map<String,Object> context, Object...args){
        try{
            Context ctx = Context.enter();
            Scriptable scope = ctx.initStandardObjects();

            for (Map.Entry<String,Object> entry : context.entrySet() ) {
                ScriptableObject.putProperty(scope,entry.getKey(),Context.javaToJS(entry.getValue(),scope));
            }

            int index = 1;
            for(Object arg : args){
                ScriptableObject.putProperty(scope,"$"+(index++),Context.javaToJS(arg,scope));
            }

            //Context.javaToJS(this, scope)
            return ctx.evaluateString(scope,
                    String.format(FORMAT,content),
                    null, 0, null);
        }finally{
            Context.exit();
        }
    }


    /**
     * 执行一段代码
     * @param content
     * @return
     */
    public static Object execute(String content){
        try{
            Context ctx = Context.enter();
            Scriptable scope = ctx.initStandardObjects();

            return ctx.evaluateString(scope, content, null, 0, null);
        }finally{
            Context.exit();
        }
    }
}
